﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;

public partial class ClientsCreateEdit : System.Web.UI.Page
{
    BankDataDataContext db = new BankDataDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Roles.IsUserInRole("Operator"))
        {
            Response.Redirect("~/Account/Login.aspx");
        }
        string companyId = null;
        if (Session["companyId"] != null)
        {
            companyId = Session["companyId"].ToString();
        }
        if (companyId != null && ViewState["isEditing"] == null)
        {
            ResetPassword.Visible = true;
            ViewState["isEditing"] = true;
            RegisterUserButton.Text = "Обновить данные пользователя";
            UserProfile editProfile = getCurrentUserProfile();
            CompanyName.Text = editProfile.Company.CompanyName;
            CompanyName.Enabled = false;
            OrganizationForm.SelectedValue = editProfile.Company.OrganitionalFormId.ToString();
            CompanySizeList.SelectedValue = editProfile.Company.CompanySizeId.ToString();
            HeadName.Text = editProfile.CompanyHead;
            CompanyAddress.Text = editProfile.Address;
            CompanyPhone.Text = editProfile.CompanyPhone;
            CompanyEmail.Text = editProfile.aspnet_User.aspnet_Membership.Email;
            HeadAddress.Text = editProfile.CompanyHeadAddress;
            HeadPhone.Text = editProfile.CompanyHeadPhone;
            CompanyHeadEmail.Text = editProfile.CompanyHeadEmail;
            Activity.Text = editProfile.Company.Activity.Name;
            CreationDate.Text = editProfile.Company.CreationDate.ToShortDateString();
            Login.Text = editProfile.aspnet_User.UserName;
            Password.Enabled = false;
            CompanyProfit.Text = editProfile.LastTwoYearsProfit.ToString();
            HaveCredit.Checked = editProfile.HasCredit;
        }
        else
        {
            string profileId = null;
            if (Session["profileId"] != null)
            {
                profileId = Session["profileId"].ToString();
            }
            if (profileId != null && ViewState["isRegisterWithProfile"] == null)
            {
                ViewState["isRegisterWithProfile"] = true;
                UserProfile editProfile = getUserProfile(Convert.ToInt32(profileId));
                CompanyName.Text = editProfile.Company.CompanyName;
                CompanyName.Enabled = false;
                OrganizationForm.SelectedValue = editProfile.Company.OrganitionalFormId.ToString();
                CompanySizeList.SelectedValue = editProfile.Company.CompanySizeId.ToString();
                HeadName.Text = editProfile.CompanyHead;
                CompanyAddress.Text = editProfile.Address;
                CompanyPhone.Text = editProfile.CompanyPhone;
                CompanyEmail.Text = editProfile.CompanyEmail;
                CompanyHeadEmail.Text = editProfile.CompanyHeadEmail;
                Activity.Text = editProfile.Company.Activity.Name;
                CreationDate.Text = editProfile.Company.CreationDate.ToShortDateString();
                HeadAddress.Text = editProfile.CompanyHeadAddress;
                HeadPhone.Text = editProfile.CompanyHeadPhone;
                CompanyProfit.Text = editProfile.LastTwoYearsProfit.ToString();
                HaveCredit.Checked = editProfile.HasCredit;
            }

        }
    }

    [System.Web.Services.WebMethodAttribute(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string[] GetCompletionList(string prefixText, int count, string contextKey)
    {
        BankDataDataContext db = new BankDataDataContext();
        var companiesName = from companies in db.Companies where companies.CompanyName.StartsWith(prefixText) select companies.CompanyName;
        return companiesName.ToArray();
    }

    protected void RegisterUserButton_Click(object sender, EventArgs e)
    {
        bool isCompleteWitoutError = false;
        if (ViewState["isEditing"] != null)
        {
            if ((bool)ViewState["isEditing"])
            {
                isCompleteWitoutError = UpdateClient();
            }
        }
        else
        {
            if (ViewState["isRegisterWithProfile"] != null)
            {
                if ((bool)ViewState["isRegisterWithProfile"])
                {
                    isCompleteWitoutError = RegisterClientWithProfile();
                    if (isCompleteWitoutError)
                    {
                        string requestId = Session["requestId"].ToString();
                        Response.Redirect("~/Operator/AddContract.aspx");
                    }
                }
            }
            else
            {
                isCompleteWitoutError = AddClient();
            }
        }
        if (isCompleteWitoutError)
        {
            Response.Redirect("~/Operator/Clients.aspx");
        }
    }

    protected UserProfile getCurrentUserProfile()
    {
        string companyId = null;
        if (Session["companyId"] != null)
        {
            companyId = Session["companyId"].ToString();
        }
        var profile = from profiles in db.UserProfiles where profiles.CompanyId == Convert.ToInt32(companyId) select profiles;
        UserProfile editProfile = profile.First();
        return editProfile;
    }

    protected UserProfile getUserProfile(int userProfileId)
    {
        var profile = from profiles in db.UserProfiles where profiles.ProfileId == userProfileId select profiles;
        UserProfile editProfile = profile.First();
        return editProfile;
    }

    protected bool UpdateClient()
    {
        UserProfile userProfile = getCurrentUserProfile();
        if (Password.Enabled)
        {
            MembershipUser user = Membership.GetUser(userProfile.aspnet_User.UserName);
            user.ChangePassword(user.GetPassword(), Password.Text);
        }
        userProfile.CompanyHead = HeadName.Text;
        userProfile.Address = CompanyAddress.Text;
        userProfile.CompanyPhone = CompanyPhone.Text;
        userProfile.CompanyEmail = CompanyEmail.Text;
        userProfile.CompanyHeadEmail = CompanyHeadEmail.Text;
        userProfile.CompanyHeadAddress = HeadAddress.Text;
        userProfile.CompanyHeadPhone = HeadPhone.Text;
        userProfile.LastTwoYearsProfit = Convert.ToInt32(CompanyProfit.Text);
        foreach (Contract contract in userProfile.Company.Contracts)
        {
            if (contract.Status.StatusId == 1)
            {
                if (!HaveCredit.Checked)
                {
                    HaveCredit.Checked = true;
                    ErrorLabel.Text = "Компания имеете кредиты";
                    return false;
                }
            }
        }
        userProfile.HasCredit = HaveCredit.Checked;
        userProfile.aspnet_User.UserName = Login.Text;
        userProfile.OperatotId = getOperatorId();
        db.SubmitChanges();
        return true;
    }

    protected int getOperatorId()
    {
        var operators = from bankOperator in db.Operators where bankOperator.UserId == (Guid)Membership.GetUser().ProviderUserKey select bankOperator;
        return operators.First().OperatorId;
    }

    protected bool RegisterClientWithProfile()
    {
        var company = from companies in db.Companies where companies.CompanyName == CompanyName.Text select companies;
        if (company.Count() == 0)
        {
            ErrorLabel.Text = "Неверное название предприятия";
            return false;
        }
        MembershipUser user;
        try
        {
            user = Membership.CreateUser(Login.Text, Password.Text, CompanyEmail.Text);
            Roles.AddUserToRole(user.UserName, "User");
        }
        catch
        {
            ErrorLabel.Text = "Логин занят";
            return false;
        }
        string profileId = null;
        if (Session["profileId"] != null)
        {
            profileId = Session["profileId"].ToString();
        }
        if (profileId != null)
        {
            UserProfile userProfile = getUserProfile(Convert.ToInt32(profileId));
            userProfile.userId = (Guid)user.ProviderUserKey;
            userProfile.CompanyId = Convert.ToInt32(company.First().CompanyId);
            userProfile.CompanyHead = HeadName.Text;
            userProfile.CompanyEmail = CompanyEmail.Text;
            userProfile.CompanyHeadEmail = CompanyHeadEmail.Text;
            userProfile.Address = CompanyAddress.Text;
            userProfile.CompanyPhone = CompanyPhone.Text;
            userProfile.CompanyHeadAddress = HeadAddress.Text;
            userProfile.CompanyHeadPhone = HeadPhone.Text;
            userProfile.LastTwoYearsProfit = Convert.ToInt32(CompanyProfit.Text);
            userProfile.HasCredit = HaveCredit.Checked;
            userProfile.OperatotId = getOperatorId();
            db.SubmitChanges();
            return true;
        }
        return false;
    }

    protected bool AddClient()
    {
        var company = from companies in db.Companies where companies.CompanyName == CompanyName.Text select companies;
        if (company.Count() == 0)
        {
            ErrorLabel.Text = "Неверное название предприятия";
            return false;
        }
        var companyIdInUserProfiles = from profiles in db.UserProfiles where profiles.CompanyId == Convert.ToInt32(company.First().CompanyId) select profiles.CompanyId;
        if (companyIdInUserProfiles.Count() > 0)
        {
            ErrorLabel.Text = "Уже существует аккаунт для данного предприятия";
            return false;
        }
        MembershipUser user;
        try
        {
            user = Membership.CreateUser(Login.Text, Password.Text, CompanyEmail.Text);
            Roles.AddUserToRole(user.UserName, "User");
        }
        catch
        {
            ErrorLabel.Text = "Логин занят";
            return false;
        }
        UserProfile userProfile = new UserProfile();
        userProfile.userId = (Guid)user.ProviderUserKey;
        userProfile.CompanyId = Convert.ToInt32(company.First().CompanyId);
        userProfile.CompanyHead = HeadName.Text;
        userProfile.CompanyEmail = CompanyEmail.Text;
        userProfile.CompanyHeadEmail = CompanyHeadEmail.Text;
        userProfile.Address = CompanyAddress.Text;
        userProfile.CompanyPhone = CompanyPhone.Text;
        userProfile.LastTwoYearsProfit = Convert.ToInt32(CompanyProfit.Text);
        userProfile.HasCredit = HaveCredit.Checked;
        userProfile.CompanyHeadAddress = HeadAddress.Text;
        userProfile.CompanyHeadPhone = HeadPhone.Text;
        userProfile.OperatotId = getOperatorId();
        db.UserProfiles.InsertOnSubmit(userProfile);
        db.SubmitChanges();
        return true;
    }

    protected void ResetPassword_Click(object sender, EventArgs e)
    {
        Password.Enabled = true;
        OperatorPasswordValidator2.Enabled = true;
        PasswordValidator.Enabled = true;
        Password.Text = Membership.GeneratePassword(9, 4);
    }
    protected void CompanyName_TextChanged(object sender, EventArgs e)
    {
        var companies = from company in db.Companies where company.CompanyName == CompanyName.Text select company;
        if (companies.Count() > 0)
        {
            Company editCompany = companies.First();
            Activity.Text = editCompany.Activity.Name;
            CreationDate.Text = editCompany.CreationDate.ToShortDateString();
            CompanySizeList.SelectedValue = editCompany.CompanySizeId.ToString();
            OrganizationForm.SelectedValue = editCompany.OrganitionalFormId.ToString();
        }
        else
        {
            Activity.Text = "";
            CreationDate.Text = "";
        }
    }
    protected void GenerateLoginButton_Click(object sender, EventArgs e)
    {
        string login = "";
        do
        {
            login = Membership.GeneratePassword(6, 2);
        } while (Membership.GetUser(login) != null);
        Login.Text = login;
    }
}